<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;">
      <el-row :gutter="10" class="mb8" style="justify-content: end; align-items: center;">
        <h1 style="margin-right: auto;">{{ warehousingTitle }}</h1>
          <el-col :span="1.5" v-if="warehousingTitle =='新增入库信息'">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="submitForm"
            >提交审核</el-button>
          </el-col>
          <el-col :span="1.5" v-if="warehousingTitle =='新增入库信息'">
            <el-button
              type="success"
              plain
              icon="Edit"
              @click="directPut"
            >直接入库</el-button>
          </el-col>

          <el-col :span="1.5" v-if="warehousingTitle =='入库详情-待审核'">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="approve"
            >审核通过</el-button>
          </el-col>
          <el-col :span="1.5" v-if="warehousingTitle =='入库详情-待审核'">
            <el-button
              type="success"
              plain
              icon="Edit"
              @click="noApprove"
            >审核未通过</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="Delete"
              @click="goBack"
            >返回</el-button>
          </el-col>
        </el-row>
      <el-form ref="warehousingRef" :model="warehousing" :rules="rules" label-width="80px" v-if="warehousingTitle == '新增入库信息'" >
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="入库单号" prop="warehousingOrderId">
              <el-input v-model="warehousing.warehousingOrderId" placeholder="请输入入库单号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库日期" prop="warehousingDate">
              <el-date-picker clearable
                v-model="warehousing.warehousingDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库人员" prop="warehousingStaff">           
              <el-select v-model="warehousing.warehousingStaff" placeholder="请选择入库人员">
                <el-option
                  v-for="dict in userList"
                  :key="dict.warehousingStaff"
                  :label="dict.nickName"
                  :value="dict.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库类型" prop="warehousingType">
              <el-select v-model="warehousing.warehousingType" placeholder="请选择入库类型">
                <el-option label="采购入库" value='采购入库' />
                <el-option label="退货入库" value='退货入库' />
                <el-option label="其他入库" value='其他入库' />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="warehousing.supplier" placeholder="请选择供应商">
                <el-option
                  v-for="dict in doctor_drug_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="制单日期" prop="documentCreationDate" >
              <el-date-picker clearable
                v-model="warehousing.documentCreationDate" 
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择制单日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="制单人员" prop="documentCreationStaff">
              <el-input v-model="warehousing.documentCreationStaff" placeholder="请输入制单人员" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="warehousing.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>  
      </el-form>

    <!-- 审核通过 或 审核未通过 状态-->
     <!-- <div>{{ warehousing }}</div>  数据 -->
     <div class="order-info" v-if="warehousingTitle == '入库详情-审核通过' || warehousingTitle == '入库详情-审核未通过' " >
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>入库单号：</label>
              <div >{{ warehousing.warehousingOrderId }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库日期：</label>
              <div>{{ warehousing.warehousingDate }}</div>
              <!-- <el-date-picker
                v-model="warehousing.warehousingDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                disabled/> -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库人员：</label>
              {{userList.find(item => item.userId == warehousing.warehousingStaff)?.nickName || '未知' }}
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库类型：</label>
              <div>{{ warehousing.warehousingType }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>供应商：</label>
              <dict-tag :options="doctor_drug_manufacturer" :value="warehousing.supplier"/>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>制单日期：</label>
              <div>{{ warehousing.documentCreationDate }}</div>
              <!-- <el-date-picker
                v-model="warehousing.documentCreationDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                disabled/>      -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>制单人员：</label>
              <div>{{ warehousing.documentCreationStaff }}</div>
              <!-- <el-input v-model="warehousing.documentCreationStaff" disabled/> -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库备注：</label>
              <div>{{ warehousing.remarks }}</div>
              <!-- <el-input v-model="warehousing.remarks" disabled/> -->
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>审核时间：</label>
              <div>{{ warehousing.auditDate }}</div>
              <!-- <el-input v-model="warehousing.auditDate" disabled/> -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>审核人员：</label>
              <div>{{ warehousing.auditStaff }}</div>
              <!-- <el-input v-model="warehousing.auditStaff" disabled/> -->
            </div>
          </el-col>
        </el-row>
     </div> 

     <div class="order-info" v-if=" warehousingTitle == '入库详情-待审核' " >
        <el-form ref="warehousingRef" :model="warehousing" :rules="rules" label-width="80px" >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="入库单号" prop="warehousingOrderId">
                <el-input v-model="warehousing.warehousingOrderId" placeholder="请输入入库单号" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库日期" prop="warehousingDate">
                <el-date-picker clearable
                  v-model="warehousing.warehousingDate"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择入库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库人员" prop="warehousingStaff">
                <template #default="scope">
                    {{userList.find(item => item.userId == warehousing.warehousingStaff)?.nickName || '未知' }}
                  </template>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库类型" prop="warehousingType">
                <el-select v-model="warehousing.warehousingType" placeholder="请选择入库类型">
                  <el-option label="采购入库" value='采购入库' />
                  <el-option label="退货入库" value='退货入库' />
                  <el-option label="其他入库" value='其他入库' />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="供应商" prop="supplier">
                <el-select v-model="warehousing.supplier" placeholder="请选择供应商">
                  <el-option
                    v-for="dict in doctor_drug_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制单日期" prop="documentCreationDate" >
                <el-date-picker clearable
                  v-model="warehousing.documentCreationDate" 
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择制单日期" disabled>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制单人员" prop="documentCreationStaff">
                <el-input v-model="warehousing.documentCreationStaff" placeholder="请输入制单人员" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="warehousing.remarks" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>  
        </el-form>
     </div> 
    </div>
    <div v-if="warehousingTitle == '入库详情-审核通过' || warehousingTitle == '入库详情-审核未通过' || warehousingTitle == '入库详情-待审核'">
      <el-table v-loading="loading" :data="intermediateList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" prop="id" width="80" />
        <el-table-column  label="药品编码" align="center" prop="drugCode" />
        <!-- 遍历 drugList 当前的药品编码和药品列表中的药品编码一致时，显示药品名称  -->
        <el-table-column label="药品名称" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.drugGenericName}}
          </template>
        </el-table-column>
        <el-table-column label="生产厂家" align="center">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value='drugList.find(item => item.drugCode === scope.row.drugCode)?.drugManufacturer'/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity" width="80"/>
        <el-table-column label="单位" align="center" prop="unit">
          <template #default="scope">
            <dict-tag :options="doctor_packaging_unit" :value="scope.row.unit"/>
          </template>
        </el-table-column>
        <el-table-column label="采购价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice}}
          </template>
        </el-table-column>
        <el-table-column label="零售价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice}}
          </template>
        </el-table-column>
        <el-table-column label="采购金额(元)" align="center" prop="purchaseAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="零售金额(元)" align="center" prop="retailAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 20px;">
        采购金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalPurchaseAmount }}</text>元 零售金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalRetailAmount }}</text>元
      </div>
    </div>

    <div v-if="warehousingTitle == '新增入库信息'">

      <el-table v-loading="loading" :data="intermediateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" width="80" />
        <el-table-column  label="药品编码" align="center" prop="drugCode" />
        <!-- 遍历 drugList 当前的药品编码和药品列表中的药品编码一致时，显示药品名称  -->
        <el-table-column label="药品名称" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.drugGenericName}}
          </template>
        </el-table-column>
        <el-table-column label="生产厂家" align="center">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value='drugList.find(item => item.drugCode === scope.row.drugCode)?.drugManufacturer'/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="80">
          <template #default="scope">
            <el-input v-model="scope.row.quantity" :min="1" size="small" @change="updateAmounts(scope.row)"
  />
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unit">
          <template #default="scope">
            <dict-tag :options="doctor_packaging_unit" :value="scope.row.unit"/>
          </template>
        </el-table-column>
        <el-table-column label="采购价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice}}
          </template>
        </el-table-column>
        <el-table-column label="零售价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice}}
          </template>
        </el-table-column>
        <el-table-column label="采购金额(元)" align="center" prop="purchaseAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="零售金额(元)" align="center" prop="retailAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="80">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="Delete(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 20px;">
        采购金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalPurchaseAmount }}</text>元 零售金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalRetailAmount }}</text>元
      </div>
      <!-- 添加按钮 -->
       <div style="text-align:center;">
        <el-button type="primary" icon="Plus" @click="handleAddDrug" >添加药品</el-button>
       </div>
    </div>
    <!-- 选择药品弹框 -->
     <el-dialog :title="Drugtitle" v-model="openDrug"  width="1000px" append-to-body>
      <el-scrollbar height="400px">
        <el-form :model="queryParamsDrug" :inline="true" label-width="68px">
          <el-form-item label="处方类别" prop="drugInformationId">
            <el-select v-model="queryParamsDrug.drugInformationId" placeholder="处方类别" clearable style="width: 100px">
              <el-option
                v-for="dict in informationList"
                :key="dict.id"
                :label="dict.drugInformationName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品名称" prop="drugGenericName">
            <el-input
              v-model="queryParamsDrug.drugGenericName"
              placeholder="请输入药品名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="生产厂家" prop="drugManufacturer">
            <el-select v-model="queryParamsDrug.drugManufacturer" placeholder="请选择生产厂家" clearable style="width: 200px">
              <el-option
                v-for="dict in doctor_drug_manufacturer"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getDrugList">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="drugList" @selection-change="handleSelectionChangeDrug">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column label="药品编码" align="center" prop="drugCode" />
          <el-table-column label="药品名称" align="center" prop="drugGenericName" />
          <el-table-column label="规格" align="center" prop="drugSpecification" />
          <el-table-column label="收费类别" align="center" prop="drugInformationId">
            <template #default="scope">
              {{informationList.find(item => item.id == scope.row.drugInformationId)?.drugInformationName || '未知' }}
            </template>
          </el-table-column>  
          <el-table-column label="生产厂家" align="center" prop="drugManufacturer">
            <template #default="scope">
              <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.drugManufacturer"/>
            </template>
          </el-table-column>
          <el-table-column label="采购价" align="center" prop="purchasePrice" />
          <el-table-column label="零售价" align="center" prop="retailPrice" />
        </el-table>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDrug">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Intermediate">
import { listIntermediate, getIntermediate, delIntermediate, addIntermediate, updateIntermediate } from "@/api/drug/intermediate";
import { listDrug, getDrug, delDrug, addDrug, updateDrug,selectDrugByCodes} from "@/api/drug/drug";
import { listInformation } from "@/api/drug/information";
import { listWarehousing, getWarehousing, delWarehousing, addWarehousing, updateWarehousing } from "@/api/drug/warehousing";
import { listUser } from "@/api/system/user";

const userList = ref([]);
const { proxy } = getCurrentInstance();
const { doctor_packaging_unit,doctor_drug_manufacturer,doctor_drug_category} = proxy.useDict('doctor_packaging_unit','doctor_drug_manufacturer','doctor_drug_category');

const intermediateList = ref([]);
const informationList = ref([]);
const drugList = ref([]);
const open = ref(false);
const openDrug = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const drugIds = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const Drugtitle =ref("");
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
const warehousingTitle= ref("");


getUserList();
/** 查询用户列表 */
function getUserList() {
  loading.value = true;
  listUser({
    pageNum: 1,
    pageSize: 9999,
  }).then(res => {
    userList.value = res.rows;
    console.log(userList.value);
  });
};
// 获取登陆用户信息
import useUserStore from '@/store/modules/user'
const user = useUserStore();

const route = useRoute();
// 修改接收方式为响应式处理
import { toRaw } from 'vue';
import { id } from "element-plus/es/locales.mjs";

onMounted(() => {
  if(route.query.formData) {
    // 获取原始数据
    warehousing.value = toRaw(JSON.parse(route.query.formData));
    // console.log(warehousing.value);
    warehousingTitle.value = toRaw(route.query.title1);
    queryParams.value.warehousingOrderId = warehousing.value.warehousingOrderId;
    getList();
  }
})


const data = reactive({
  warehousing: {},
  form: {},
  queryParamsDrug:{
    pageNum: 1,
    pageSize: 9999,
    drugInformationId: null,
    drugCode: null,
    drugGenericName: null,
    drugManufacturer: null,
    drugStatus: null,
    creationTime: null,
    drugInventory:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    warehousingOrderId: null,
    // drugCode: null,
    // quantity: null,
    // unit: null,
    // purchaseAmount: null,
    // retailAmount: null
  },
  rules: {
    warehousingOrderId: [
      { required: true, message: "入库单号不能为空", trigger: "blur" }
    ],
    warehousingDate: [
      { required: true, message: "入库日期不能为空", trigger: "blur" }
    ],
    warehousingStaff: [
      { required: true, message: "入库人员不能为空", trigger: "change" }
    ],
    warehousingType: [
      { required: true, message: "入库类型不能为空", trigger: "change" }
    ],
    supplier: [
      { required: true, message: "供应商不能为空", trigger: "change" }
    ],
  },
  intermediateDrugList: [] // 中间表数据
});


const { queryParams, form, rules,queryParamsDrug,warehousing} = toRefs(data);
// 计算属性
const totalPurchaseAmount = computed(() => {
  return intermediateList.value.reduce((sum, item) => sum + parseFloat(item.purchaseAmount || 0), 0).toFixed(2);
});

const totalRetailAmount = computed(() => {
  return intermediateList.value.reduce((sum, item) => sum + parseFloat(item.retailAmount || 0), 0).toFixed(2);
});
/** 查询药品信息列表 */
function getDrugList() {
  loading.value = true;
  queryParamsDrug.value.params = {};
  listDrug(queryParamsDrug.value).then(response => {
    drugList.value = response.rows;
    loading.value = false;
  });
}
/** 查询药品信息分类列表 */
function getlistInformationList() {
  loading.value = true;
  listInformation(queryParams.value).then(response => {
    informationList.value = response.rows;
    loading.value = false;
  });
}
// 多选框选中数据
function handleSelectionChangeDrug(selection) {
  drugIds.value = selection.map(item => item.id);
}
// 保存选择的药品
function submitFormDrug() {
  if (drugIds.value.length === 0) {
    proxy.$modal.msgWarning("请选择药品");
    return;
  }
  // 先判断是否有重复的药品编码 如果重复就去重
  // 创建临时Set存储已存在的药品编码
  const existingCodes = new Set(intermediateList.value.map(item => item.drugCode));
   // 过滤重复药品（保留最后一个出现的）
   const uniqueDrugs = drugIds.value.reduceRight((acc, drugId) => {
    const drug = drugList.value.find(d => d.id === drugId);
    if (drug && !existingCodes.has(drug.drugCode)) {
      existingCodes.add(drug.drugCode);
      acc.push(drug);
    }
    return acc;
  }, []).reverse();
   // 添加非重复药品
   uniqueDrugs.forEach(selectedDrug => {
    intermediateList.value.push({
      id: intermediateList.value.length + 1,
      warehousingOrderId: warehousing.value.warehousingOrderId,
      drugCode: selectedDrug.drugCode,
      quantity: 1,
      unit: selectedDrug.packagingUnit,
      purchaseAmount: (1 * selectedDrug.purchasePrice).toFixed(2),
      retailAmount: (1 * selectedDrug.retailPrice).toFixed(2)
    });
  });
  // 清楚选择的药品
  drugIds.value = [];
  openDrug.value = false;
 }
// 添加金额计算方法
const updateAmounts = (row) => {
  const drug = drugList.value.find(item => item.drugCode === row.drugCode);
  if (drug) {
    row.purchaseAmount = parseFloat((row.quantity * drug.purchasePrice).toFixed(2));
    row.retailAmount = parseFloat((row.quantity * drug.retailPrice).toFixed(2));
  }
}
// 删除药品
function Delete(row) {
  const index = intermediateList.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    intermediateList.value.splice(index, 1);
    // 删除后重新排序序号
    intermediateList.value.forEach((item, idx) => {
      item.id = idx + 1;
    });
  }
}


function goBack() {
  proxy.$router.push({ 
    path: "/1/warehousing",
    query: { refresh: Date.now() }  // 添加随机参数强制刷新
  });
}
/** 查询药品入库和药品中间列表 */
function getList() {
  // console.log(warehousing.warehousingOrderId);
  // queryParams.value.warehousingOrderId = warehousing.value.warehousingOrderId;
  loading.value = true;
  listIntermediate(queryParams.value).then(response => {
    intermediateList.value = response.rows;
    // console.log(intermediateList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  openDrug.value = false;
  open.value = false;
  reset();
}

// 表单重置
function reset() {
 
  form.value = {
    id: null,
    warehousingOrderId: null,
    drugCode: null,
    quantity: null,
    unit: null,
    purchaseAmount: null,
    retailAmount: null
  };
  warehousing.value = {
    id: null,
    warehousingOrderId: null,
    warehousingDate: null,
    warehousingStaff: null,
    warehousingType: null,
    supplier: null,
    documentCreationDate: null,
    documentCreationStaff: null,
    remarks: null,
    totalPurchaseAmount: null,
    totalRetailAmount: null,
    auditStatus: null,
    auditDate: null,
    auditStaff: null
  };
  proxy.resetForm("intermediateRef");
  proxy.resetForm("warehousingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  
}
// 药品添加按钮操作
function handleAddDrug(){
  openDrug.value = true;
  Drugtitle.value = "选择药品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getIntermediate(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改药品入库和药品中间";
  });
}

/** 提交审核 */
function submitForm() {
  warehousing.value.totalPurchaseAmount=totalPurchaseAmount.value
  warehousing.value.totalRetailAmount=totalRetailAmount.value
  warehousing.value.auditStatus = 0;

  if(intermediateList.value.length==0){
    proxy.$modal.msgWarning("请添加药品");
    return;
  }
  proxy.$refs["warehousingRef"].validate(valid => {
    addWarehousing(warehousing.value).then(response => {
      intermediateList.value.forEach(item => {
      const intermediateItem = {
          ...item,
        };
         // 将intermediateItem转换为JSON字符串
         const intermediateJson = JSON.stringify(intermediateItem);
         // 调用接口
         addIntermediate(intermediateJson).then(response => {
          open.value = false;
      });
    });
      proxy.$modal.msgSuccess("提交成功"); 
      goBack()
      open.value = false;
    });
  });
}
// 直接入库
function directPut(){
  warehousing.value.totalPurchaseAmount=totalPurchaseAmount.value
  warehousing.value.totalRetailAmount=totalRetailAmount.value
  warehousing.value.auditStatus = 1;
  warehousing.value.auditStaff= user.name;
  warehousing.value.auditDate = formatDateTime(new Date());
  if(intermediateList.value.length==0){
    proxy.$modal.msgWarning("请添加药品");
    return;
  }
  proxy.$refs["warehousingRef"].validate(valid => {
    addWarehousing(warehousing.value).then(response => {
      intermediateList.value.forEach(item => {
      const intermediateItem = {
          ...item,
        };
         // 将intermediateItem转换为JSON字符串
         const intermediateJson = JSON.stringify(intermediateItem);
         // 调用接口修改药品的库存
         addIntermediate(intermediateJson).then(response => {
          listDrug({drugCode:item.drugCode}).then(response => { 
            const drug = response.rows[0];
            updateDrug({
              id: drug.id,
              drugCode: drug.drugCode,
              drugInventory: drug.drugInventory + item.quantity,
            })
          })
          // 根据药品编码查询信息 添加入库数量
          open.value = false;
      });
    });
      proxy.$modal.msgSuccess("提交成功"); 
      goBack()
      open.value = false;
    });
  });
}
// 格式为 YYYY-MM-DD HH:MM:SS 的时间字符串
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 审核通过 approve
function approve() {
  warehousing.value.auditStatus = 1;
  warehousing.value.auditStaff= user.name;
  warehousing.value.auditDate = formatDateTime(new Date());
  updateWarehousing(warehousing.value).then(res => {
    proxy.$modal.msgSuccess("审核成功");
    goBack()
  })
}
// 审核不通过 noApprove
function noApprove() {
  warehousing.value.auditStatus = 2;
  warehousing.value.auditStaff= user.name;
  warehousing.value.auditDate = formatDateTime(new Date());
  if (warehousing.value.remarks == null) {
    proxy.$modal.msgError("请填写审核不通过原因");
    return;
  }
  updateWarehousing(warehousing.value).then(res => {
    proxy.$modal.msgSuccess("审核成功");
    goBack()
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品入库和药品中间编号为"' + _ids + '"的数据项？').then(function() {
    return delIntermediate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/intermediate/export', {
    ...queryParams.value
  }, `intermediate_${new Date().getTime()}.xlsx`)
}

// getList();
getDrugList();
getlistInformationList();
</script>
<style>
.order-info {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item label {
  width: 80px;
  color: #606266;
  flex-shrink: 0;
}

:deep(.el-input),
:deep(.el-select) {
  flex: 1;
}
</style>